package com.example.testdemo.noticeBar;

import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import com.example.testdemo.R;

/**
 * Created by MrYan on 2018/9/14.
 * 仿微信消息弹窗
 */

public class NoticeWindowActivity extends Activity {
    private static final String TAG = "NoticeWindowActivity";
    private WindowManager windowManager;
    private WindowManager.LayoutParams params;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notice_window);
        initWindowManager();
    }

    private void initWindowManager() {

        windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        params = new WindowManager.LayoutParams();

        //这个 params.type 在Android 7.0 之后就不能再使用 TYPE_TOAST 了，说什么滥用（CTMD)
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
        params.format = PixelFormat.TRANSPARENT;

        params.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN//忽略系统通知栏（就是能把通知栏盖住）
                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL//类似焦点之类的东西吧，不设置的话，点击外部也可以消失
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;//设置不影响其他操作

        // 设置通知栏的长和宽
        params.width = windowManager.getDefaultDisplay().getWidth();
        params.height = 200;
        params.gravity = Gravity.TOP;
    }

    public void showNoticeWindow(View view) {
        createFloatView("lkkkkkkkkk");
    }


    private void createFloatView(String str) {

        View view = LayoutInflater.from(this).inflate(R.layout.view_bar, null);
        //在这里你可以解析你的自定义的布局成一个View
        if (view.getParent() == null) {
            windowManager.addView(view, params);
            Log.d(TAG, "createFloatView: addView()");
        } else {
            windowManager.updateViewLayout(view, params);
            Log.d(TAG, "createFloatView: updateViewLayout()");
        }


        view.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (v != null) {
                            windowManager.removeViewImmediate(v);
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:

                        break;
                }
                return true;
            }
        });

    }
}
